import React, { useEffect, useState, useMemo } from 'react';
import { Select, Form, Tooltip, Input, message, Radio } from 'antd';
import { layout2 } from '@/utils/config';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import DebounceMultipleSelect from '@/components/DebounceMultipleSelect';
import {
  queryTakeUserList,
  editSingleMessage,
  updateTakeUserBatch,
  updateRefundUserBatch,
  updateAreaBatch,
  getAreaListOp,
  queryAreaCode,
  queryTypeDaiNaChannel,
  updateDaiNaUserBatch,
  updateDaiNa,
  screenUpdateDaiNa
} from '../service';
import { find, isEmpty } from 'lodash';
import styles from './index.module.less';

const { Option } = Select;

export default ({ visible, handleOk, handleCancel, clearSelect, item = {}, type, selectedRow, totalAreaList, listData, showDaifaTool, total, query }) => {
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(false);
  const [userData, setUserData] = useState([]); // 拿货员列表
  const [refundUserData, setRefundUserData] = useState([]); // 退货员列表
  const [daiNaUserData, setDaiNaUserData] = useState([]); // 代拿货员列表
  const [dainaChannelData, setDainaChannelData] = useState([]); // 代拿渠道列表
  // const [areaCodeList, setAreaCodeList] = useState([]);

  const is_zjf_user = JSON.parse(localStorage.getItem('ISZJF') || sessionStorage.getItem('ISZJF')); //找家纺仓库用户
  const [form] = Form.useForm();

  const daiNaSwitchValue = Form.useWatch('daiNaSwitch', form);

  const obj = find(totalAreaList, ['name', item.shopArea]);

  useEffect(() => {
    if (visible) {
      if (type == 0) {//编辑时请求列表数据
        form.setFieldsValue({...item, shopArea:obj?.id, daiNaSwitch: item.daiNaSwitch || 0});
      }
      handleUserList();
      handleRefundUserList();
      getTypeDaiNaChannel();
      handleDaiNaUserList();
    }
  }, [visible])

    //代拿渠道列表
    const getTypeDaiNaChannel = async () => {
        const { data, success } = await queryTypeDaiNaChannel();
        if (success) {
            setDainaChannelData(data);
        }
      }

  //拿货员列表
  const handleUserList = async (username) => {
    const { data, success } = await queryTakeUserList({ username, current: 1, size: 2000, businessType: 3 });
    if (success) {
      setUserData(data);
    }
  }

  //退货员列表
  const handleRefundUserList = async (username) => {
    const { data, success } = await queryTakeUserList({ username, current: 1, size: 2000, businessType: 4 });
    if (success) {
      setRefundUserData(data);
    }
  }

  //代拿拿货员列表
  const handleDaiNaUserList = async (username) => {
    const { data, success } = await queryTakeUserList({ username, current: 1, size: 2000, businessType: 8 });
    if (success) {
      setDaiNaUserData(data);
    }
  }

  //区域编码列表
  const getAreaListFunc = async () => {
    setLoading(true);
    const { data, success } = await getAreaListOp();
    setLoading(false);
    if (success) {
      setAreaCodeList(data);
      if(type == 0){
        const obj = find(data,['name', item.shopArea]);
        form.setFieldsValue({
          shopArea:obj?.id
        })
      }
    }
  }

  function fetchAreaCode(areaCode) {
    return new Promise( async (resolve, reject)=>{
      setFetching(true);
      const { data, success } = await queryAreaCode({ areaCode });
      setFetching(false);
      if(success && data?.length){
        const newArr = [];
        data.map(item => {
          newArr.push({
            label: item.name,
            value: item.id,
          })
        })
        resolve(newArr);
      }else{
        reject();
      }
    })
  }

  //校验
  const onOk = () => {
    form.validateFields().then(val => {
      handleSubmit(val);
    })
  }

  //提交
  const handleSubmit = async (val) => {
    const { takeUserId, refundUserId, shopArea, daiNaUserId, daiNaChannelId, daiNaSwitch } = val;
    setLoading(true);
    if (type == 0) {// 单条修改提交
      const param = {
        ...val,
        storeId: item.storeId,
        id: item.id
      }
      const { success } = await editSingleMessage(param)
      if (success) {
        handleOk();
        handleCancel();
        clearSelect();
      }
    } else if (type == 1) {// 批量分配拿货员
      const param = selectedRow.map(item => {
        return Object.assign(item, { takeUserId })
      })
      const { success } = await updateTakeUserBatch(param)
      if (success) {
        handleOk();
        handleCancel();
        clearSelect();
      }
    } else if (type == 2) {// 批量分配退货员
      const param = selectedRow.map(item => {
        return Object.assign(item, { refundUserId })
      })
      const { success } = await updateRefundUserBatch(param)
      if (success) {
        handleOk();
        handleCancel();
        clearSelect();
      }
    } else if (type == 3) {// 批量设置区域编码
      const param = selectedRow.map(item => {
        return Object.assign(item, { shopArea })
      })
      const { success } = await updateAreaBatch(param)
      if (success) {
        handleOk();
        handleCancel();
        clearSelect();
      }
    } else if (type == 'daifa') {// 批量设置代发拿货员
        const param = selectedRow.map(item => {
          return Object.assign({ storeId: item.storeId }, { daiNaUserId })
        })
        const { success } = await updateDaiNaUserBatch(param)
        if (success) {
          handleOk();
          handleCancel();
          clearSelect();
        }
      } else if(type == 'daifaSelect') {//批量设置代发
       const param = selectedRow.map(item => {
            return Object.assign({ storeId: item.storeId }, { daiNaChannelId, daiNaSwitch })
        })
        const { success, msg = '' } = await updateDaiNa(param)
        if (success) {
          message.success(msg);
          handleOk();
          handleCancel();
          clearSelect();
        }
     } else if(type == 'daifaScreen') {//根据筛选条件设置代发
        const param = {...query, daiNaChannelId, daiNaSwitch, }
        const { success, msg = '' } = await screenUpdateDaiNa(param)
        if (success) {
          message.success(msg);
          handleOk();
          handleCancel();
          clearSelect();
        }
     }
    setLoading(false);
  }

  const onCancel = () => {
    form.resetFields();
    handleCancel();
  }

  //渲染交接员工
  const renderSubUser = (item) => {
    if (item.name) {
      if (item.account) {
        return item.name + '(' + item.account + ')'
      } else {
        return item.name
      }
    } else {
      return ''
    }
  }

  const optionUserList = !isEmpty(userData) && userData.map(item => (<Option key={item.id} value={item.id}><Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip></Option>))
  const optionRefundUserList = !isEmpty(refundUserData) && refundUserData.map(item => (<Option key={item.id} value={item.id}><Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip></Option>))
  const optionDainaChannelList = !isEmpty(dainaChannelData) && dainaChannelData.map(item => (<Option key={item.id} value={item.id}><Tooltip title={item.channelName}>{item.channelName}</Tooltip></Option>))
  const optionDainaUserList = !isEmpty(daiNaUserData) && daiNaUserData.map(item => (<Option key={item.id} value={item.id}><Tooltip title={renderSubUser(item)}>{renderSubUser(item)}</Tooltip></Option>))

  const renderTitle = () => {
    switch (type) {
      case 0:
        return '编辑'
      case 'daifa':
        return '分配代拿拿货员'
      case 'daifaSelect':
        return '批量设置代拿'
      case 'daifaScreen':
        return '批量设置代拿'
      case 1:
        return '批量分配拿货员'
        break;
      case 2:
        return '批量分配退货员'
        break;
      case 3:
        return '批量设置区域编码'
        break;
      default:
        break;
    }
  }

  //门店数渲染
  const countRender = useMemo(() => {
    if(type == 'daifaSelect') {
        return selectedRow.length;
    } else if(type == 'daifaScreen') {
        return total;
    }
 }, [type, selectedRow, listData])

  return (
    <CommonModal
      title={item.id ? '编辑' : renderTitle()}
      visible={visible}
      minHeight='120px'
      onOk={onOk}
      onCancel={onCancel}
      width="600px"
    >
      <Form
        {...layout2}
        form={form}
        className={styles.formStyle}
        style={{ marginRight: '16px' }}
        name='store-edit-modal-form'
      >
        {/* 统一添加范围 */}
        {/* <Form.Item label="修改范围" name='range' rules={[{ required: true, message: '请选择' }]}>
            <Radio.Group>
                <Radio value="apple">针对勾选项</Radio>
                <Radio value="pear">针对筛选项</Radio>
            </Radio.Group>
        </Form.Item> */}
        {type == 0 ?
          <Form.Item label="门店名称">
            <span>{item.shopName}</span>
          </Form.Item> : null}
        {(type == 0 || type == 1) ?
          <Form.Item
            name="takeUserId"
            label="拿货员"
            // initialValue={item.takeUserId || null}
            rules={[{ required: true, message: '请选择拿货员' }]}
          >
            <Select
              showSearch
              placeholder='请选择拿货员'
              filterOption={(input, option) => {
                return option.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }}
              // onSearch={handleUserList}
              allowClear
            >
              {optionUserList}
            </Select>
          </Form.Item> : null}
          {
            ((type == 0 && is_zjf_user) || type == 'daifa') ?
            <Form.Item
            name="daiNaUserId"
            label="代拿拿货员" 
            rules={[{ required: true, message: '代拿拿货员' }]}
          >
            <Select
              showSearch
              placeholder='请选择代拿拿货员'
              filterOption={(input, option) => {
                return option.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }}
              // onSearch={handleRefundUserList}
              allowClear
            >
              {optionDainaUserList}
            </Select>
          </Form.Item> : null
          }
        {(type == 0 || type == 2) ?
          <Form.Item
            name="refundUserId"
            label="退货员"
            // initialValue={item.refundUserId || null}
            rules={[{ required: true, message: '请选择退货员' }]}
          >
            <Select
              showSearch
              placeholder='请选择退货员'
              filterOption={(input, option) => {
                return option.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }}
              // onSearch={handleRefundUserList}
              allowClear
            >
              {optionRefundUserList}
            </Select>
          </Form.Item> : null}
        {(type == 0 || type == 3) ?
          <Form.Item
            name="shopArea"
            label="区域编码"
            rules={[{required: type == 3, message:'请选择区域编码'}]}
          >
            <DebounceMultipleSelect
              showSearch
              allowClear
              needFetchFirst
              labelInValue={false}
              placeholder="请输入关键词搜索"
              notFoundContent={fetching ? '加载中' : '暂无数据'}
              fetchOptions={fetchAreaCode}
              defaultValue={obj?.id}
            />
          </Form.Item> : null}
        {type == 0 ?
          <Form.Item
            name="orderBy"
            label="门店顺序"
            rules={[{ pattern:/^[1-9]\d*$/, message: '请输入整数数字' }]}
          >
            <Input placeholder='请输入门店顺序' />
          </Form.Item> : null}
          {((type == 0 && is_zjf_user == false) || ['daifaSelect', 'daifaScreen'].includes(type)) ?
          <>
          {
            ['daifaSelect', 'daifaScreen'].includes(type) ?
            <Form.Item
            label="门店数"
          >
            {countRender}
          </Form.Item>: ''
          }
          {
            type == 0 && <Form.Item
              name="checkPayTime"
              label='采购付款节点'
              initialValue={item.checkPayTime || 0}
              rules={[{ required: true }]}
            >
              <Select placeholder="请选择采购付款节点">
                <Option value={0}>采购时结算</Option>
                <Option value={1}>清点时结算</Option>
              </Select>
            </Form.Item>
          }
          {/* {
            showDaifaTool ? <>
            <Form.Item
            name="daiNaSwitch"
            label="是否开启代拿"
            rules={[{required: true, message:'请选择是否开启代拿'}]}
          >
            <Select>
                <Option value={0}>否</Option>
                <Option value={1}>是</Option>
            </Select>
          </Form.Item>
          {
            daiNaSwitchValue ? <Form.Item
            name="daiNaChannelId"
            label="代拿渠道"
            rules={[{ required: true, message: '请选择代拿渠道' }]}
            extra={['daifaSelect', 'daifaScreen'].includes(type) ? '开启后，该门店的自发拿货商品的拿货任务，将会自动推送给代拿渠道仓库生成代拿任务': ''}
          >
            <Select
              showSearch
              placeholder='请选择代拿渠道'
              allowClear
            >
              {optionDainaChannelList}
            </Select>
          </Form.Item> : ''
          }
            </>
            : ''
          } */}
          </>
        : null}
      </Form>
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}